package com.cskaoyan.demo1.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Description：
 * @Author：BLUEBLANK
 * @Date：2024/4/7 15:00
 */

@WebServlet("/wx/old/*")
public class WxOldServlet extends HttpServlet {
    String storagePath;

    @Override
    public void init() throws ServletException {
        storagePath = (String) getServletContext().getAttribute("storagePath");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        // 获取文件名  形如 /ikun.jpg
        String fileName = uri.substring(uri.lastIndexOf("/"));

        // 去对应地址读文件  然后写入浏览器
        File file = new File(storagePath, fileName);

        FileInputStream in = new FileInputStream(file);

        ServletOutputStream outputStream = resp.getOutputStream();

        byte[] bytes = new byte[1024];

        int len;
        while ((len = in.read(bytes)) != -1) {
            outputStream.write(bytes,0,len);
        }

        in.close();


    }
}
